<template>
  <div v-if="jsonData" class="result-section">
    <div class="json-header">
      <el-button type="primary" size="small" @click="handleCopy" :loading="copying">
        <el-icon><document-copy /></el-icon>
        复制JSON
      </el-button>
    </div>
    <pre class="json-viewer">{{ formattedJson }}</pre>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { DocumentCopy } from '@element-plus/icons-vue'

const props = defineProps<{
  jsonData: any
}>()

const copying = ref(false)

// 格式化JSON数据
const formattedJson = computed(() => {
  return JSON.stringify(props.jsonData, null, 2)
})

// 复制JSON数据
const handleCopy = async () => {
  if (!formattedJson.value) return
  
  copying.value = true
  try {
    if (navigator.clipboard) {
      await navigator.clipboard.writeText(formattedJson.value)
    } else {
      // 使用传统的复制方法作为备选方案
      const textarea = document.createElement('textarea')
      textarea.value = formattedJson.value
      textarea.style.position = 'fixed'
      textarea.style.left = '-9999px'
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
    }
    ElMessage.success('复制成功')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  } finally {
    copying.value = false
  }
}
</script>

<style scoped>
.result-section {
  margin-top: 20px;
}

.json-header {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
}

.json-viewer {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: monospace;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>